import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Location} from '@angular/common';

import {NzMessageService} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {RoleMoudel} from '../role-moudel';
import {RoleService} from '../role.service';
import {ResourceService} from '../../resource/resource.service';
// import {ResourceService} from '../../resource/resource.service';
// import {RoleService} from '../role.service';

@Component({
    selector: 'app-show',
    templateUrl: './show.component.html',
})
export class ShowComponent implements OnInit {
    roleForm: FormGroup;

    idOfRes: any[] = [];

    roleMoudel: RoleMoudel = new RoleMoudel();

    constructor(private fb: FormBuilder,
                private location: Location,
                private activityRoute: ActivatedRoute,
                private msg: NzMessageService,
                private roleService: RoleService,
                private resourceService: ResourceService
    ) {
        this.roleForm = this.fb.group({
            id: [0],
            nickName: ['', [Validators.required, Validators.maxLength(6)]],
            resId: ['', Validators.required],
        });
    }

    ngOnInit() {
        const id = this.activityRoute.snapshot.paramMap.get('id');
        if (id) {
            this.roleService.showRole(id).subscribe(res => {
                this.roleMoudel.id = res['id'];
                this.roleMoudel.nickName = res['nickName'];
                this.roleMoudel.resId = res['res'];
                this.roleForm.patchValue({
                    id: this.roleMoudel['id'],
                    nickName: this.roleMoudel['nickName'],
                    resId: this.roleMoudel['resId'].length !== 0 ? '1' : '',
                });
                console.log(this.roleMoudel['resId'].length);

                this.resourceService.getResourceList().subscribe(re => {
                    const ret = [];
                    for (let i = 0; i < re['list'].length; i++) {
                        ret.push({
                            key: re['list'][i]['id'].toString(),
                            title: re['list'][i]['name'],
                        });
                    }
                    this.idOfRes = ret;
                    for (let i = 0; i < this.roleMoudel['resId'].length; i++) {
                        for (let j = 0; j < this.idOfRes.length; j++) {
                            if (this.roleMoudel['resId'][i] === this.idOfRes[j]['key']) {
                                this.idOfRes[j].direction = 'right';
                            }
                        }
                    }
                });
            });
        } else {
            this.getResource();
        }
    }

    /**
     * 获取资源列表
     */
    getResource() {
        this.resourceService.getResourceList().subscribe(res => {
            const ret = [];
            for (let i = 0; i < res['list'].length; i++) {
                ret.push({
                    key: res['list'][i]['id'].toString(),
                    title: res['list'][i]['name'],
                });
            }
            this.idOfRes = ret;
        });
    }

    /**
     * 选中回调
     * @param $event
     */
    select($event) {
        console.log('nzSelectChange', $event);
    }

    /**
     * 改变回调
     * @param $event
     */
    change($event) {
        let ret = this.roleMoudel['resId'];

        for (let i = 0; i < $event['list'].length; i++) {
            const temp = $event['list'][i]['key'].toString();
            if ($event['to'] === 'right') {
                ret.push(temp);
            } else {
                const index = ret.indexOf(temp);
                ret = [...ret.slice(0, index), ...ret.slice(index + 1, ret.length)];
            }
        }
        this.roleMoudel['resId'] = ret;
        if (ret && ret.length > 0) {
            this.roleForm.patchValue({resId: ret});
        } else {
            this.roleForm.patchValue({resId: ''});
        }
    }

    /**
     * 提交
     */
    submit() {
        const res = this.roleForm.value;
        this.roleMoudel['id'] = res['id'];
        this.roleMoudel['nickName'] = res['nickName'];

        console.log(JSON.stringify(this.roleMoudel));

        this.roleService.addRole(this.roleMoudel).subscribe(__ => {
            this.msg.success('保存成功');
            this.location.back();
        }, e => {
            console.error(e);
            // this.msg.success('保存失败');
        });
    }

}
